package com.gnerv.cms.freemarker.tag;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gnerv.cms.dto.CatalogDTO;
import com.gnerv.cms.dto.CatalogSearchDTO;
import com.gnerv.cms.freemarker.FreemarkerComponent;
import com.gnerv.cms.service.ICatalogService;
import com.gnerv.cms.utils.FreemarkerUtils;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/4/3
 */
@FreemarkerComponent("g_catalog")
public class CatalogTagDirective implements TemplateDirectiveModel {

    @Resource
    private ICatalogService catalogService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        String parentId = FreemarkerUtils.getParamToString("parentId", map);
        String catalogId = FreemarkerUtils.getParamToString("catalogId", map);
        String size = FreemarkerUtils.getParamToString("size", map);
        TemplateModel tm;
        if (!StringUtils.isEmpty(parentId)) {
            CatalogSearchDTO catalogSearchDTO = new CatalogSearchDTO();
            catalogSearchDTO.setParentId(parentId);
            Page<CatalogDTO> catalogPage = catalogService.listCatalog(catalogSearchDTO, 1L, Long.valueOf(size));
            List<CatalogDTO> catalogs = catalogPage.getRecords();
            tm = builder.build().wrap(catalogs);
            environment.setVariable("catalogs", tm);
        } else if (!StringUtils.isEmpty(catalogId)) {
            CatalogDTO catalog = catalogService.selectCatalog(catalogId);
            tm = builder.build().wrap(catalog);
            environment.setVariable("catalog", tm);
        }
        templateDirectiveBody.render(environment.getOut());
    }

}
